package com.simu.towercrane.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.util.android.view.CCPullLisvtView;
import cc.util.android.view.CCPullLisvtView.CCOnListViewListener;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.cn.adapters.BaseImageAndTextListAdapter;
import com.cn.adapters.InsuranceImageAndTextListAdapter;
import com.cn.adapters.VendorImageAndTextListAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.simu.constant.TableConstant;
import com.simu.constant.TableConstant.Collection;
import com.simu.constant.TableConstant.InsuranceBroker;
import com.simu.constant.TableConstant.User;
import com.simu.towercrane.R;
import com.simu.towercrane.adapter.ErshouListAdapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class InsuranceFragment extends BaseFragmentTwo{
	cc.util.android.view.CCPullLisvtView mInsuranceListView;
	InsuranceImageAndTextListAdapter mAdapter=null;
	ArrayList<Map<String, Object>> mInsuranceListHashMap;
	String userIdString="";
	Context mContext;	
	final int FITSTSHOWNUM=10;
	final int LOADMORENUM=5;
	int currentWhere;
	List<String> mWatchedInstrokerList;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initData();	
		mWatchedInstrokerList=new ArrayList<String>();		
	}
	 @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
		 View view=inflater.inflate(R.layout.fragment_insurance, null);
		 mInsuranceListView=(CCPullLisvtView) view.findViewById(R.id.insurance_list);
		 mInsuranceListHashMap=new  ArrayList<Map<String,Object>>();
		 mAdapter=new InsuranceImageAndTextListAdapter(getActivity(),mInsuranceListHashMap, R.layout.insurance_listview_item_view,
	 			 new String[]{			 				  
			 				  TableConstant.InsuranceBroker.headPortrait,
			 				  TableConstant.InsuranceCompany.logo,
			 				  TableConstant.InsuranceCompany.companyName,
			 				  TableConstant.InsuranceBroker.brokerName,
			 				  TableConstant.InsuranceBroker.price,
			 				  TableConstant.InsuranceBroker.description,
			 				  TableConstant.watched
			 				} ,
	 			  new int[]{
			 				R.id.iv_broker,	
			 				R.id.iv_logo,			 						 			
			 				R.id.tv_company,
			 				R.id.tv_broker,
			 				R.id.tv_price,
			 				R.id.tv_description,
			 				R.id.collo_rb
		 					});
		 mInsuranceListView.setAdapter(mAdapter);
		 mInsuranceListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), false, true));
		 setRefreshListener();	
		 return view;					
	 }

	private void initData() {
		// TODO Auto-generated method stub
		mContext=getActivity();
		SharedPreferences sPreferences=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
		userIdString=sPreferences.getString(Collection.userID,"");
	}

boolean y=true;
	private void setRefreshListener() {
		// TODO Auto-generated method stub
		mInsuranceListView.setCCOnListViewListener(new CCOnListViewListener() {
			
			@Override
			public void onRefresh(CCPullLisvtView view) {
				// TODO Auto-generated method stub				
				getWachtedUserAndRefreshData();
			}
			
			@Override
			public void onLoadMore(CCPullLisvtView view) {
				// TODO Auto-generated method stub
			//	mInsuranceListView.stopLoadMore();
				getWachtedUserAndLoadMoreData();
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public void getWachtedUserAndRefreshData(){
	    @SuppressWarnings("rawtypes")
		AVQuery query=AVQuery.getUserQuery();
	    query.whereEqualTo(User.objectId, userIdString);
	    query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> users, AVException e) {
				// TODO Auto-generated method stub
				if(e==null&&users!=null){
					AVObject object=users.get(0);
					AVRelation<AVObject> watchedIns=object.getRelation(User.watchedInsuranceBroker);
					AVQuery<AVObject> watchedInsQu= watchedIns.getQuery();
					watchedInsQu.findInBackground(new FindCallback<AVObject>() {

						@Override
						public void done(List<AVObject> lists, AVException e) {
							// TODO Auto-generated method stub
							
							mWatchedInstrokerList.clear();
						    if(lists!=null&&e==null){
						    	//所有收藏的经纪人
						    	for(AVObject avObject:lists){
						    		String watchedInstrokId=avObject.getObjectId()+"";
						    		Log.d("watchedInstrokId", watchedInstrokId);
						    		mWatchedInstrokerList.add(watchedInstrokId);
						    	}
						    }
						    refreshData();//加载完收藏的经纪人后加载所有经纪人
						}
					});
				}
			}
		});
	    
	}
	public void refreshData(){
		 AVQuery<AVObject> mBrokerQuery=new AVQuery<AVObject>("InsuranceBroker");
		 mBrokerQuery.include("company");
		 mBrokerQuery.limit(FITSTSHOWNUM);		
		 mBrokerQuery.findInBackground(new FindCallback<AVObject>() {			
			@Override
			public void done(List<AVObject> mBrokers, AVException arg1) {
				// TODO Auto-generated method stub
				mInsuranceListHashMap.clear();
				if(mBrokers!=null){
					currentWhere=mBrokers.size();
					for(AVObject broker :mBrokers){
						final HashMap<String, Object> oneMap=new HashMap<String, Object>();					
					    AVFile headIMFile=broker.getAVFile(TableConstant.InsuranceBroker.headPortrait);
					    String headImgUrl="";
						if(headIMFile!=null){
							headImgUrl=headIMFile.getUrl();
						}
						oneMap.put(TableConstant.InsuranceBroker.headPortrait,headImgUrl );
						AVObject comAvObject=broker.getAVObject("company");						
						AVFile logoIMFile=comAvObject.getAVFile(TableConstant.InsuranceCompany.logo);
						String logoUrlString="";
						if(logoIMFile!=null){
							logoUrlString=logoIMFile.getUrl()+"";
						}
						oneMap.put(TableConstant.InsuranceCompany.logo,  logoUrlString);
						oneMap.put(TableConstant.InsuranceCompany.companyName,  comAvObject.getString(TableConstant.InsuranceCompany.companyName)+"");
						oneMap.put(TableConstant.InsuranceBroker.brokerName, broker.getString(TableConstant.InsuranceBroker.brokerName)+"");
						oneMap.put(TableConstant.InsuranceBroker.telNo, broker.getString(TableConstant.InsuranceBroker.telNo)+"" );
						oneMap.put(TableConstant.InsuranceBroker.objectId, broker.getString(TableConstant.InsuranceBroker.objectId)+"");
						oneMap.put(TableConstant.InsuranceBroker.price,  broker.getString(TableConstant.InsuranceBroker.price)+"");  
						oneMap.put(TableConstant.InsuranceBroker.description,  broker.getString(TableConstant.InsuranceBroker.description)+"");
						String instrokerId=broker.getObjectId();
						boolean watched=mWatchedInstrokerList.contains(instrokerId);
						oneMap.put(TableConstant.watched,watched+"");	
						oneMap.put(InsuranceBroker.self,broker);
						
						mInsuranceListHashMap.add(oneMap);					
						mAdapter.notifyDataSetChanged();
						mInsuranceListView.stopRefresh();
					}
				}
			}
		});
	}
	
	@SuppressWarnings("unchecked")
	public void getWachtedUserAndLoadMoreData(){
		@SuppressWarnings("rawtypes")
		AVQuery query=AVQuery.getUserQuery();
	    query.whereEqualTo(User.objectId, userIdString);
	    query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> users, AVException e) {
				// TODO Auto-generated method stub
				if(e==null&&users!=null){
					AVObject object=users.get(0);
					AVRelation<AVObject> watchedIns=object.getRelation(User.watchedInsuranceBroker);
					AVQuery<AVObject> watchedInsQu= watchedIns.getQuery();
					watchedInsQu.findInBackground(new FindCallback<AVObject>() {

						@Override
						public void done(List<AVObject> lists, AVException e) {
							// TODO Auto-generated method stub
							
							mWatchedInstrokerList.clear();
						    if(lists!=null&&e==null){
						    	//所有收藏的经纪人
						    	for(AVObject avObject:lists){
						    		String watchedInstrokId=avObject.getObjectId()+"";
						    		Log.d("watchedInstrokId", watchedInstrokId);
						    		mWatchedInstrokerList.add(watchedInstrokId);
						    	}
						    }
						    loadMoreData();
						}
					});
				}
			}
		});
	}	
	//Loaddata
	public void loadMoreData(){
		 AVQuery<AVObject> mBrokerQuery=new AVQuery<AVObject>("InsuranceBroker");
		 mBrokerQuery.include("company");
		 mBrokerQuery.skip(currentWhere);
		 mBrokerQuery.setLimit(LOADMORENUM);
		 mBrokerQuery.findInBackground(new FindCallback<AVObject>() {					
			@Override
			public void done(List<AVObject> mBrokers, AVException arg1) {
				// TODO Auto-generated method stub
				if(mBrokers!=null){					
					currentWhere+=mBrokers.size();
					if(mBrokers.size()==0){
						//Toast.makeText(getActivity(), "数据加载完毕 共"+currentWhere+"条数据", Toast.LENGTH_SHORT).show();								
					}
					for(AVObject broker :mBrokers){								
						final HashMap<String, Object> oneMap=new HashMap<String, Object>();					
					    AVFile headFile=broker.getAVFile(TableConstant.InsuranceBroker.headPortrait);
					    String imgUrl="";
						if(headFile!=null){
							imgUrl=headFile.getUrl();
						}
						AVObject comAvObject=broker.getAVObject("company");
						oneMap.put(TableConstant.InsuranceBroker.headPortrait,imgUrl );
						AVFile logoIMFile=comAvObject.getAVFile(TableConstant.InsuranceCompany.logo);
						String logoUrlString="";
						if(logoIMFile!=null){
							logoUrlString=logoIMFile.getUrl();
						}
						oneMap.put(TableConstant.InsuranceCompany.logo,  logoUrlString);
						oneMap.put(TableConstant.InsuranceCompany.companyName,  comAvObject.getString(TableConstant.InsuranceCompany.companyName)+"");
						oneMap.put(TableConstant.InsuranceBroker.brokerName, broker.getString(TableConstant.InsuranceBroker.brokerName)+"");
						oneMap.put(TableConstant.InsuranceBroker.telNo, broker.getString(TableConstant.InsuranceBroker.telNo)+"" );
						oneMap.put(TableConstant.InsuranceBroker.objectId, broker.getString(TableConstant.InsuranceBroker.objectId)+"");
						oneMap.put(TableConstant.InsuranceBroker.price,  broker.getString(TableConstant.InsuranceBroker.price)+"");  
						oneMap.put(TableConstant.InsuranceBroker.description,  broker.getString(TableConstant.InsuranceBroker.description)+"");
						String instrokerId=broker.getObjectId();
						boolean watched=mWatchedInstrokerList.contains(instrokerId);
						oneMap.put(TableConstant.watched,watched+"");	
						oneMap.put(InsuranceBroker.self,broker);
						
						mInsuranceListHashMap.add(oneMap);
						mAdapter.notifyDataSetChanged();								
					}		
					mInsuranceListView.stopLoadMore();
				}			
			}
		});
	}
	
}
